/**
 * @description 关于用户及登录的相关数据操作
 */

import { getUserInfo, login, logout } from '@/api/user'
import { resetRouter } from '@/router'
import { removeToken, setToken } from '@/utils/auth'

const getDefaultState = () => {
  const userId = sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')).userId : ''
  return {
    userId: userId,
    name: '',
    avatar: '',
    userInfo: ''
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password, verificationCode } = userInfo
    const cipherMode = 0 // 1 - C1C3C2，0 - C1C2C3，默认为1
    let password1, username1
    console.log(Number(process.env.VUE_APP_IS_ENCRYPT))
    if (process.env.VUE_APP_IS_ENCRYPT === '1') {
      const sm2Encrypt = require('sm2js').default
      password1 = sm2Encrypt(password, process.env.VUE_APP_login_key, cipherMode)
      username1 = sm2Encrypt(username.trim(), process.env.VUE_APP_login_key, cipherMode)
    } else {
      const sm2Encrypt = require('sm2js').default
      password1 = sm2Encrypt(password, process.env.VUE_APP_login_key, cipherMode)
      username1 = sm2Encrypt(username.trim(), process.env.VUE_APP_login_key, cipherMode)
    }
    return new Promise((resolve, reject) => {
      login({ username: username1, password: password1, verificationCode })
        .then((response) => {
          const { data } = response.data
          commit('SET_USERINFO', data)
          sessionStorage.setItem('userInfo', JSON.stringify(data))
          setToken(data.token)
          localStorage.setItem('USERInfo', JSON.stringify(data))
          localStorage.setItem('DepartmentCode', data.departmentCode)
          localStorage.setItem('districtCode', data.districtCode)
          localStorage.setItem('userType', data.userTypeId)
          // localStorage.setItem("publicKey", data.publicKey);
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const userId = JSON.parse(sessionStorage.getItem('userInfo')).userId || ''
      getUserInfo({ userId: userId })
        .then((response) => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录！')
          }
          const { userId } = data
          commit('SET_NAME', userId)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 用户退出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken()
          resetRouter()
          sessionStorage.clear()
          localStorage.clear()
          commit('RESET_STATE')
          location.reload()
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 删除用户信息
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
